<?php

namespace app\models;

use Yii;


class Permission extends \yii\db\ActiveRecord
{
    public $p_name;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%auth_item}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['name','required','on'=>['create','edit']],
            ['name','string','max'=>20,'on'=>['create','edit']],
            ['name','unique','on'=>['create']],
            ['name','unique','on'=>['edit'],'filter'=>['<>','name',$this->name]],

            ['description','required','on'=>['create','edit']],
            ['description','string','max'=>100,'on'=>['create','edit']],

            ['rule_name','safe'],

            ['data','safe'],

            ['p_name','safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => '权限标识',
            'description' => '权限名称',
            'rule_name' => '规则名称',
            'data' => '数据',
        ];
    }

    public static function tree()
    {
        $data = self::find()->where(['and','type=2','name like "%/*"'])->asArray()->all();
        foreach ($data as &$p){
            $c = explode('/',$p['name']);
            $p['child'] = self::find()->where(['and','type=2','name !="'.$p['name'].'"','name like "'.$c[0].'%"'])->asArray()->all();
        }
        return $data;
    }

    public function createPermission()
    {
        if ($this->validate()){
            $auth = Yii::$app->authManager;
            $permission = $auth->createPermission($this->name);
            $permission->description = $this->description;
            if ($auth->add($permission)){
                if ($this->p_name){
                    $parent = $auth->getPermission($this->p_name);
                    if ($auth->canAddChild($parent,$permission)){
                        $auth->addChild($parent,$permission);
                    }
                }
                return true;
            }
        }
        return false;
    }

    public function editPermission()
    {
        if ($this->validate()){
            $auth = Yii::$app->authManager;
            $permission = $auth->createPermission($this->name);
            $permission->description = $this->description;
            if ($auth->update($this->getOldAttribute('name'),$permission)){
                return true;
            }
        }
        return false;
    }


}
